package com.indusfo.spc.controller;

import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.MatVerService;
import com.indusfo.spc.untlis.ExcelUtil;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import jdk.nashorn.internal.runtime.ECMAException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author liub
 * @Date 2019/11/20 9:38
 * @Version 1.0
 */
@Controller
@RequestMapping("/service/matVer")
public class MatVerController {

    @Autowired
    private MatVerService matVerService;

    //查询
    @RequestMapping(value = "/queryMatVer")
    @ResponseBody
    public JSONObject queryMatVer(MatVer matVer) {
        JSONObject json = matVerService.queryMatVer(matVer);
        return json;
    }

    //新增
    @RequestMapping(value = "/insertMatVer", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject insertMatVer(MatVer matVer) {
        JSONObject json = matVerService.insertMatVer(matVer);
        return json;
    }

    //修改
    @RequestMapping(value = "/updateMatVer", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateMatVer(MatVer matVer) {
        JSONObject json = matVerService.updateMatVer(matVer);
        return json;
    }

    //删除
    @RequestMapping(value = "/deleteMatVer", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deleteMatVer(@RequestParam("matVerIds") List<Integer> matVerIds, Integer dataState) {
        dataState = 2;
        JSONObject json = matVerService.deleteMatVer(matVerIds, dataState);
        return json;
    }

    //启用停用
    @RequestMapping(value = "/definedMatVer", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject definedMatVer(@RequestParam("matVerIds") List<Integer> matVerIds, Integer dataState) {
        JSONObject json = matVerService.deleteMatVer(matVerIds, dataState);
        return json;
    }


    /**
     * @Author 熊冰 保存工序流程
     * @Date 2019/11/23 10:34
     */
    @RequestMapping(value = "/saveMatFlow", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveMatFlow(@RequestBody MatVer matVer) {
        try {
            JSONObject json = matVerService.saveMatFlow(matVer);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return JSONObject.build(JSONObject.ERROR, "系统异常，请联系管理员");
        }
    }

    /**
     * @Author 熊冰 保存维修流程
     * @Date 2019/11/23 10:34
     */
    @RequestMapping(value = "/saveMatRepair", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveMatRepair(@RequestBody MatVer matVer) {
        try {
            JSONObject json = matVerService.saveMatRepair(matVer);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return JSONObject.build(JSONObject.ERROR, "系统异常，请联系管理员");
        }
    }

    /**
     * @Author 熊冰 导入标准流程 强制导入工序流程 和 维修流程
     * @Date 2019/11/26 10:09
     * matId 物料id
     * matVerId 标准流程id
     * leadStation  是否导入工位
     * leadBom  是否导入关键物料
     * leadBadpheno  是否导入不良现象
     * leadDete  是否导入采集项目
     * leadRepairDete  是否导入维修流程采集项目
     * leadRepairFlow  是否导入维修流程工序
     */
    @RequestMapping(value = "/leadMatVer", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject leadMatVer(Integer matId, Integer matVerId, Integer leadBom, Integer leadStation, Integer leadBadpheno, Integer leadDete, Integer leadRepairDete, Integer leadRepairFlow) {
        JSONObject json = matVerService.leadMatVer(matId, matVerId, leadBom, leadStation, leadBadpheno, leadDete, leadRepairDete, leadRepairFlow);
        return json;
    }

    /**
     * 级联删除物料版本下的工序流程和维修流程
     */
    @RequestMapping(value = "/deleteCascadeMatVer", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deleteCascadeMatVer(@RequestParam("matVerIds") List<Integer> matVerIds, Integer dataState) {
        dataState = 2;
        try {
            return matVerService.deleteCascadeMatRepair(matVerIds, dataState);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONObject.build(JSONObject.ERROR,"系统异常，请联系管理员");
        }
    }

    /**
     * 工艺文件库查询
     */
    @RequestMapping(value = "/queryMatVerByProfile")
    @ResponseBody
    public JSONObject queryMatVerByProfile(MatVer matVer) {
        JSONObject json = matVerService.queryMatVerByProfile(matVer);
        return json;
    }



    @RequestMapping("/uploadFileMatVer")
    @ResponseBody
    public JSONObject uploadFileMatVer(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        //定义一个message对象用于向前台传输数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.setStatus(JSONObject.SUCCESS);
        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        if (wb == null) {
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                jsonObject.setStatus(JSONObject.ERROR);
                jsonObject.setMsg("未找到需要导入的表格");
                errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
            } else {
                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    jsonObject.setStatus(JSONObject.ERROR);
                    jsonObject.setMsg("未找到需要导入的数据，请确认物料信息表格是否保存！！！");
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认料信息表格是否保存！！！"));
                } else {
                    List<UploadMatVer> uploadMatVerList = new ArrayList<>();
                    for (int i = 1; i <= rowCount; i++) {
                        boolean needAdd = true;
                        //获取到每一行的每一列的数据
                        //物料编号
                        String matCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
                        //工艺版本名称
                        String matVerName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
                        UploadMatVer uploadMatVer = new UploadMatVer(matCode, matVerName);
                        //将excel中的每一行数据存储进行检查
                        String result = matVerService.checkExcelContent(uploadMatVer);
                        if (result != null) {
                            errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
                            needAdd = false;
                        }
                        for (int j = 1; j < i; j++) {
                            //判断物料编码  物料名称是否重复
                            String oldMatCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 0, false);
                            String oldMatVerName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 1, false);
                            if (!StringUtils.isBlank(matCode) && oldMatCode.equals(matCode) && !StringUtils.isBlank(matVerName) && matVerName.equals(oldMatVerName)) {
                                needAdd = false;
                                errorDatas.add(ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同工艺版本名称"));
                            }
                        }
                        if (needAdd) {
                            uploadMatVerList.add(uploadMatVer);
                        } else {
                            jsonObject.setStatus(JSONObject.ERROR);
                            jsonObject.setMsg("导入数据中存在异常信息");
                        }

                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (jsonObject.getStatus().equals(JSONObject.ERROR) && !way) {
                        jsonObject.setMsg(jsonObject.getMsg() + ",中止导入");
                    } else {
                        if (uploadMatVerList.size() > 0) {
                            try {
                                long start = System.currentTimeMillis();
                                matVerService.updateListUploadMatVer(uploadMatVerList);
                                long end = System.currentTimeMillis();
                                System.out.println(end-start);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                jsonObject.setMsg(StringUtils.isBlank(jsonObject.getMsg()) ? "导入成功" : jsonObject.getMsg());
                                if ("导入成功".equals(jsonObject.getMsg())) {
                                    jsonObject.setStatus(JSONObject.SUCCESS);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                jsonObject.setMsg("导入失败");
                            }
                        }
                    }
                }
            }
        }
        jsonObject.setData(GsonUtil.toJson(errorDatas));
        return JSONObject.build(JSONObject.SUCCESS, jsonObject.getMsg(), errorDatas);
    }
}
